package com.shfl.task.logic.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageInfo;
import com.shfl.task.logic.bean.TaskJob;
import com.shfl.task.logic.bean.TaskLog;
import com.shfl.task.logic.bean.TaskLogError;
import com.shfl.task.logic.constants.CommonConstants;
import com.shfl.task.logic.mapper.TaskLogMapper;
import com.shfl.task.logic.model.info.TaskLogInfo;
import com.shfl.task.logic.model.response.TaskLogResponse;
import com.shfl.task.logic.service.TaskJobService;
import com.shfl.task.logic.service.TaskLogErrorService;
import com.shfl.task.logic.service.TaskLogService;
import com.shfl.task.pagehelper.PageHelperUtils;
import com.shfl.task.pagehelper.Pageable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.Objects;

@Service
public class TaskLogServiceImpl implements TaskLogService {

    @Autowired
    private TaskLogMapper taskLogMapper;

    @Autowired
    private TaskLogErrorService taskLogErrorService;


    @Autowired
    private TaskJobService taskJobService;

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void insertSelective(TaskLog taskLog) {
        taskLogMapper.insertSelective(taskLog);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void insertSelective(TaskLogInfo taskLogInfo) {
        TaskLog taskLog = new TaskLog();
        BeanUtil.copyProperties(taskLogInfo, taskLog, false);
        taskLogMapper.insertSelective(taskLog);
        if (Objects.equals(taskLog.getTaskStatus(), CommonConstants.TaskLogStatus.FAILURE.getCode())) {
            TaskLogError taskLogError = new TaskLogError();
            taskLogError.setContent(taskLogInfo.getErrorContent());
            taskLogError.setLogId(taskLog.getId());
            taskLogError.setTaskId(taskLog.getTaskId());
            taskLogErrorService.insertSelective(taskLogError);
            TaskJob taskJob = new TaskJob();
            taskJob.setId(taskLog.getTaskId());
            taskJob.setJobStatus(CommonConstants.JobStatus.ERROR_CLOSE.getCode());
            taskJobService.updateByPrimaryKeySelective(taskJob);
        }
    }

    @Override
    public PageInfo<TaskLogResponse> findPage(Pageable pageable, Map<String, Object> objectMap) {
        PageHelperUtils.startPageWithCount(pageable);
        return new PageInfo<>(taskLogMapper.findList(objectMap));
    }
}
